const router = require('koa-router')();
const svgCaptcha = require('svg-captcha');
const tools = require('../../module/tools');

let DB = require('../../module/db.js'); 

router.get('/', async (ctx) => {
  // ctx.body = '用户登陆';
  await ctx.render('admin/login');
});

router.post('/doLogin', async (ctx) => {
  console.log(ctx.request.body);
  let username = ctx.request.body.username;
  let password = ctx.request.body.password;
  let md5Password = tools.md5(password);
  let code = ctx.request.body.code;
  if(code.toLocaleLowerCase() === ctx.session.code.toLocaleLowerCase()){
    //验证码输入正确   判断账号密码是否正确
    //后台还需要验证用户名密码是否合法(未实现)
    let result = await DB.find('adminUser', {'username': username, 'password': md5Password});
    // console.log(result);
    if(result.length > 0){
      //数据库匹配成功  设置session  重定向进入首页界面
      ctx.session.userInfo = result[0];
      //更新用户表中的登陆时间为当前的操作时间
      await DB.update('adminUser', {"_id": DB.getObjectId(result[0]._id)}, {"time": new Date()});
      //重定向进入首页界面
      ctx.redirect(ctx.state.__HOST__ + '/admin');
    }else{
      await ctx.render('admin/error', {
        message: '账号或密码错误',
        redirect: ctx.state.__HOST__+'/admin/login'
      });
    }
  }else{
    await ctx.render('admin/error', {
      message: '验证码错误',
      redirect: ctx.state.__HOST__ + '/admin/login'
    })
  }
  
  
  
});

/* 验证码请求 */
router.get('/code', async (ctx) => {
  const captcha = svgCaptcha.create({
    size: 4,
    fontSize: 50,
    width: 100,
    height: 40,
    background: "#cc9966"
  })
  //校验验证码时先把验证码的数字存储到session中
  ctx.session.code = captcha.text;
  ctx.response.type = 'image/svg+xml';
  ctx.body = captcha.data;
});

module.exports = router.routes();